package com.lq.springai.model;

import com.lq.springai.config.AIConfig;
import com.lq.springai.entity.ModelParams;
import com.lq.springai.entity.ChatRequest;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

/**
 * * Author 30783
 * * Data：2025/6/26 14:04
 */
@Slf4j
@Service
public class OnlineServiceModel {

    @Resource
    private AIConfig aiConfig;

    private ChatClient chatClient;

    // 历史消息列表，用于存储聊天的历史记录
    private static List<Message> historyMessage = new ArrayList<>();
    // 历史消息列表的最大长度，用于限制历史记录的数量
    private static final int maxLen = 1000;

    /**
     * 文字对话框
     * @param chatRequest
     * @return
     */
    public Flux<ServerSentEvent<String>> streamChat(ChatRequest chatRequest,ModelParams modelParams) {
        //用户id
        String userId = chatRequest.getUserId();

        log.info("用户："+chatRequest.getUserId()+"，问题："+chatRequest.getMessage());

        historyMessage.add(new UserMessage(chatRequest.getMessage()));
        if (historyMessage.size() > maxLen) {
            historyMessage = historyMessage.subList(historyMessage.size() - maxLen - 1, historyMessage.size());
        }

        //todo:后续优化，这个地方需要实现切换模型
        if(chatClient == null){
            chatClient = aiConfig.chatClient(modelParams);
        }

        return chatClient.prompt(new Prompt(historyMessage))
                .stream().content().map(content -> ServerSentEvent.builder(content).event("message").build())
                //问题回答结速标识,以便前端消息展示处理
                .concatWithValues(ServerSentEvent.builder("[DONE]").build())
                .onErrorResume(e -> Flux.just(ServerSentEvent.builder("Error: " + e.getMessage()).event("error").build()));
    }
}
